package com.example.myapplication.adapter;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;
import com.example.myapplication.bean.LotDevice;

import java.util.List;

public class MyDeviceListAdapter extends BaseAdapter {

    private Context context;
    private List<LotDevice> list;
    private Class target;

    public MyDeviceListAdapter(Context context, List<LotDevice> list, Class target) {
        this.context = context;
        this.list = list;
        this.target = target;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LotDevice lotDevice = (LotDevice) getItem(position);
        Log.d("zoubo", "device_id:" + lotDevice.getDevice_id());
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(R.layout.item_lotdevice, null);
            viewHolder = new ViewHolder();
            viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
            viewHolder.deviceStatus = (TextView) view.findViewById(R.id.device_status);
            //将ViewHolder存储在View中
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.deviceName.setText(lotDevice.getDevice_name());
        viewHolder.deviceStatus.setText(lotDevice.getStatus());
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断设备状态
                if (lotDevice.getStatus().equals("ONLINE")) {
                    //在线状态
                    Intent intent = new Intent(context, target);
                    intent.putExtra("device", lotDevice);
                    context.startActivity(intent);
                } else {
                    Toast.makeText(context, "设备非在线状态不可操作", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        });
        return view;
    }

    public void setData(List<LotDevice> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    class ViewHolder {
        TextView deviceName;
        TextView deviceStatus;
    }
}
